// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var localNotifications, localGrades;
var bgPage = chrome.extension.getBackgroundPage();
var isSearching;

logOut = function () {
	bgPage.clearPollTimers();
	bgPage.count = 0;
    bgPage.setBadge();
	localStorage.removeItem("token");
	localStorage.removeItem("grades");
	localStorage.removeItem("notifications");
	loggedOrNot();
}


displayErrorMsg = function (http) {
	var errorMsg = "";
	if (http.status == 0) {
		errorMsg = "Something wrong happened. Please, try again and if the problem persist, please, report it. Check your connection meanwhile";
	} else if (http.status != 200) {
		errorMsg = http.statusText;
	} else if (http.responseText.indexOf("Unauthorized") > -1 || http.responseText.indexOf("Unauthroized") > -1) {
		errorMsg = "Invalid Password";
	} else if (http.responseText.indexOf("User Not Found") > -1){
		errorMsg = "Invalid User Name";
	}
	
	$("#miss").html(errorMsg);
	$('#miss').show();
	document.forms["myForm"].onsubmit = validateLoginForm;
}

loadXML = function (txt) {
    var txt2 = txt.substr(txt.indexOf("<xs:schema"), txt.indexOf("</xs:schema>"));
    var txt = txt.replace(txt2, "").replace("?","");
    return new DOMParser().parseFromString(txt,"text/xml");
}
searchBroadcasts = function(regex) {
    var results  = [];
	var items = localNotifications;
    for (i = items.length - 1; i > -1; i--) {
		var item = items[i];
		if (item.attributes["notification_type"].value == "Broadcast") {
			
			if (item.attributes["notification_text"].value.toLowerCase().search(regex) > -1
			|| item.attributes["notification_type"].value.toLowerCase().search(regex) > -1
			|| item.attributes["notification_title"].value.toLowerCase().search(regex) > -1) {
				results.unshift(item);
			}
		}
	}
	console.log("searched grades: " + results.length + "," + localNotifications.length + ", " + items.length);
	displayBroadcasts(results);
}
searchGrades = function (regex) {
	var results  = [];
	var items = localGrades
    for (i = items.length - 1; i > -1; i--) {
		var item = items[i];
		
        if (item.attributes["course_code"].value.toLowerCase().search(regex) > -1            
        || item.attributes["element_type"].value.toLowerCase().search(regex) > -1
		|| item.attributes["element_name"].value.toLowerCase().search(regex) > -1
		|| item.attributes["scored_grade"].value.toLowerCase().search(regex) > -1) {
			results.unshift(item);
		}
	}
	console.log("searched grades: " + results.length + "," + localGrades.length + ", " + items.length);
	displayGrades(results);
}
searchNotifications = function(regex) {
    var results  = [];
	var items = localNotifications;
    for (i = items.length - 1; i > -1; i--) {
		var item = items[i];
		if (item.attributes["notification_type"].value != "Broadcast") {
			if (item.attributes["course_code"].value.toLowerCase().search(regex) > -1            
			|| item.attributes["notification_text"].value.toLowerCase().search(regex) > -1
			|| item.attributes["notification_type"].value.toLowerCase().search(regex) > -1
			|| item.attributes["notification_title"].value.toLowerCase().search(regex) > -1) {
				results.unshift(item);
			}
		}
	}
	console.log("searched grades: " + results.length + "," + localNotifications.length + ", " + items.length);
	displayNotifications(results);
}

onSearchInput = function(input) {
	isSearching = input.value.length > 0;
	var str = input.value.toLowerCase();
	var regex;
	try {
		regex = new RegExp(str);
	} catch (err) {
		regex = str;
	}
    switch (input.id) {
        case "broadcasts_search": searchBroadcasts(regex); break;
        case "notifications_search": searchNotifications(regex); break;
        case "grades_search": searchGrades(regex); break;
    }
}

formatGrade = function (item) {
	element = '<div id="item-' + i + '" class="item">\n<h5>' + 
    item.attributes["course_code"].value + ": " + 
    item.attributes["element_name"].value + '</h5>'
    + '<div class="desc">You got in the ' + item.attributes["element_type"].value + ": " + item.attributes["scored_grade"].value + "/" + item.attributes["full_grade"].value + '</div> </div>';
	return element
}

formatNotification = function(item) {
	var element = '<div id="' + Date.parse(item.attributes["notification_date"].value) + '" class="item">\n<h5>' + (item.attributes["course_code"]? item.attributes["course_code"].value + ": " : "") + item.attributes["notification_title"].value + '</h5> <div class="desc ' + item.attributes["notification_read"].value + '">' 
    + item.attributes["notification_text"].value + '</div> <input type="hidden" id="type" value="' + item.attributes["notification_type"].value + '"> </div>';
	return element;
}

formatBroadcast = function (item) {
	var index = item.attributes["notification_text"].value.indexOf("has replied");
    var index = (index < 0? item.attributes["notification_text"].value.indexOf("broadcast") : index);
    var title =  item.attributes["notification_title"].value.toUpperCase() + " from " +item.attributes["notification_text"].value.substr(0, index);
    var element = '<div id="' + Date.parse(item.attributes["notification_date"].value) + '" class="item">\n<h5>' + title + '</h5> <div class="desc ' + item.attributes["notification_read"].value + '">' 
    + item.attributes["notification_text"].value + '</div> <input type="hidden" id="type" value="' + item.attributes["notification_type"].value + '"> </div>';
	return element;
}

displayGrades = function (data) {
    if(!data || data.length == 0) {
        $("#Grades").html("<h5>No Grades Yet</h5>");
        return ;
    }
	if(data.length > 0) {
		$("#Grades").html('');
	}
    console.log("display grades");
    for (i = data.length - 1; i > -1; i--) {
		var element = formatGrade(data[i]);
        $("#Grades").append(element);
    }
}

displayNotifications = function (data) {
    if (!data || data.length == 0) {
        $("#Notifications").html("<h5> No Notifications </h5>");
        return;
    }
	if (data.length > 0) {
		$("#Notifications").html('');
	}
    
    for (i = data.length - 1; i > -1; i--) {
        if(data[i].attributes["notification_type"].value != "Broadcast") {
		    var element = formatNotification(data[i]);
            $("#Notifications").append(element);
        }
    }
}

displayBroadcasts = function (data) {
	if (!data || data.length == 0) {
        $("#Broadcasts").html("<h5> No BroadCasts </h5>");
        return;
    }
	$("#Broadcasts").html('');
	for (i = data.length - 1; i > -1; i--) {
        if(data[i].attributes["notification_type"].value == "Broadcast") {
		    var element = formatBroadcast(data[i]);
            $("#Broadcasts").append(element);
        }
    }
	
	if ($("#Broadcasts").children().length == 0) {
		$("#Broadcasts").html("<h5> No BroadCasts </h5>");
	}
}

setData = function() {
	if (localStorage.notifications) {
		localNotifications = loadXML(localStorage.notifications).getElementsByTagName("Notifications");
	} else {
		localNotifications = [];
	}
	if (localStorage.grades) {
		localGrades = loadXML(localStorage.grades).getElementsByTagName("Grades");
	} else {
		localGrades = [];
	}
}
//hadi begin

function loggedOrNot(){
    if(localStorage["token"]){
        $('#notlogged').hide();
        $('#logged').show();
		setData();
        displayNotifications(localNotifications);
		displayBroadcasts(localNotifications);
        displayGrades(localGrades);
		
        return true;
    } else{
        $('#logged').hide();
        $('#notlogged').show();
        return false;
    }
}

function validateLoginForm()
{
    var username=document.forms["myForm"]["username"].value;
    var password=document.forms["myForm"]["password"].value;
    if (username==null || username=="" || password==null || password=="") {
		var errorMsg = "";
		if (username==null || username=="") {
			errorMsg = "User Name Cannot Be Empty";
		}
		if (password==null || password=="") {
			errorMsg += (errorMsg.length > 0? " And " : "") + "Password Cannot Be Empty";
		}
		$('#miss').html(errorMsg);
        $('#miss').show();
        return false;
    } else {
        document.forms["myForm"].onsubmit = undefined;
	    bgPage.getToken(username,password);
		console.log("send Request for Token");
		$("#miss").html("LOADING . . .");
		$('#miss').show();
        return false;
	}
}

//hadi end

$(document).ready(function () {
    loggedOrNot();
    bgPage.count = 0;
    bgPage.setBadge();
});

//getTranscriptGrades();